package com.sendtion.xrichtext;

import com.sendtion.xrichtext.utils.TypedAttrUtils;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ScrollView;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;

import java.util.ArrayList;

/**
 * RichTextView
 *
 * @since 2021-06-22
 */
public class RichTextView extends ScrollView {
    private static final int EDIT_PADDING = 10;
    private static final int INT_500 = 500;
    private static final int INT_10 = 10;
    private static final int INT_16 = 16;
    private static final int INT_8 = 8;
    private static final int INT_50 = 50;
    private static final int INT_15 = 15;
    private static final float FLOAT_2 = 2.75f;
    private static final float FLOAT_0 = 0.5f;
    private int viewTagIndex = 1;
    private DirectionalLayout allLayout;
    private int editNormalPadding = 0;
    private ClickedListener btnListener;
    private ArrayList<String> imagePaths;
    private String keywords;
    private OnRtImageClickListener onRtImageClickListener;

    /**
     * 自定义属性
     **/
    private int rtImageHeight = 0;
    private int rtImageBottom = INT_10;
    private String rtTextInitHint = "没有内容";
    private int rtTextSize = INT_16;
    private Color rtTextColor = Color.RED;
    private int rtTextLineSpace = INT_8;

    /**
     * RichTextView
     *
     * @param context
     * @param attrs
     */
    public RichTextView(Context context, AttrSet attrs) {
        this(context, attrs, "");
    }

    /**
     * RichTextView
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public RichTextView(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        rtImageHeight = attrs.getAttr("rt_editor_image_height").get().getIntegerValue();
        rtImageBottom = attrs.getAttr("rt_editor_image_bottom").get().getIntegerValue();
        rtTextSize = attrs.getAttr("rt_editor_text_size").get().getDimensionValue();
        rtTextLineSpace = attrs.getAttr("rt_editor_text_line_space").get().getDimensionValue();
        rtTextColor = attrs.getAttr("rt_editor_text_color").get().getColorValue();
        rtTextInitHint = attrs.getAttr("rt_editor_text_init_hint").get().getStringValue();

        rtImageHeight = TypedAttrUtils.getDimensionPixelSize(attrs, "rt_view_image_height", 0);

        imagePaths = new ArrayList<>();

        allLayout = new DirectionalLayout(context);
        allLayout.setOrientation(DirectionalLayout.VERTICAL);
        LayoutConfig layoutParams = new LayoutConfig(LayoutConfig.MATCH_PARENT,
                LayoutConfig.MATCH_CONTENT);
        allLayout.setPadding(INT_50, INT_15, INT_50, INT_15);
        addComponent(allLayout, layoutParams);

        btnListener = new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (component instanceof DataImageView) {
                    DataImageView imageView = (DataImageView) component;
                    if (onRtImageClickListener != null) {
                        onRtImageClickListener.onRtImageClick(imageView.getAbsolutePath());
                    }
                }
            }
        };

        DirectionalLayout.LayoutConfig firstEditParam = new DirectionalLayout.LayoutConfig(
                LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT);
        Text firstText = createTextView(rtTextInitHint, dip2px(context, EDIT_PADDING));
        allLayout.addComponent(firstText, firstEditParam);
    }

    private int dip2px(Context context, float dipValue) {
        return (int) (dipValue * FLOAT_2 + FLOAT_0);
    }

    /**
     * OnRtImageClickListener
     *
     * @since 2021-06-22
     */
    public interface OnRtImageClickListener {
        /**
         * onRtImageClick
         *
         * @param imagePath
         */
        void onRtImageClick(String imagePath);
    }

    public void setOnRtImageClickListener(OnRtImageClickListener onRtImageClickListener) {
        this.onRtImageClickListener = onRtImageClickListener;
    }

    /**
     * 清除所有的view
     */
    public void clearAllLayout() {
        allLayout.removeAllComponents();
    }

    /**
     * 获得最后一个子view的位置
     *
     * @return int
     */
    public int getLastIndex() {
        int lastEditIndex = allLayout.getChildCount();
        return lastEditIndex;
    }

    /**
     * 生成文本输入框
     *
     * @param hint
     * @param paddingTop
     * @return Text
     */
    public Text createTextView(String hint, int paddingTop) {
        Text textView = (Text) LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_rich_textview, null, false);

        textView.setTag(viewTagIndex++);
        textView.setPadding(editNormalPadding, paddingTop, editNormalPadding, paddingTop);
        textView.setHint(hint);
        textView.setTextSize(rtTextSize, Text.TextSizeType.PX);
        textView.setLineSpacing(rtTextLineSpace, 1.0f);
        textView.setTextColor(rtTextColor);
        return textView;
    }

    /**
     * 生成图片View
     *
     * @return DependentLayout
     */
    private DependentLayout createImageLayout() {
        DependentLayout layout = (DependentLayout) LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_edit_imageview, null, false);
        layout.setTag(viewTagIndex++);
        Component closeView = layout.findComponentById(ResourceTable.Id_image_close);
        closeView.setVisibility(Component.INVISIBLE);
        DataImageView imageView = (DataImageView) layout.findComponentById(ResourceTable.Id_edit_imageView);
        imageView.setClickedListener(btnListener);
        return layout;
    }

    /**
     * 关键字高亮显示
     *
     * @param target 需要高亮的关键字
     * @param text 需要显示的文字
     * @return spannable 处理完后的结果，记得不要toString()，否则没有效果
     * SpannableStringBuilder textString = TextUtilTools.highlight(item.getItemName(), KnowledgeActivity.searchKey);
     * vHolder.tv_itemName_search.setText(textString);
     */
    public static StringBuilder highlight(String text, String target) {
        StringBuilder spannable = new StringBuilder(text);
        return spannable;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    /**
     * 在特定位置插入EditText
     *
     * @param index 位置
     * @param editStr EditText显示的文字
     */
    public void addTextViewAtIndex(final int index, CharSequence editStr) {
        Text textView = createTextView("", EDIT_PADDING);
        if (keywords != null) {
            StringBuilder textStr = highlight(editStr.toString(), keywords);
            textView.setText(textStr.toString());
        } else {
            textView.setText(editStr.toString());
        }

        getContext().getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override
            public void run() {
                allLayout.addComponent(textView, index);
            }
        });
    }

    /**
     * 在特定位置添加ImageView
     *
     * @param index
     * @param imagePath
     */
    public void addImageViewAtIndex(final int index, final String imagePath) {
        if (imagePath == null) {
            return;
        }
        imagePaths.add(imagePath);
        DependentLayout imageLayout = createImageLayout();
        final DataImageView imageView = (DataImageView) imageLayout.findComponentById(ResourceTable.Id_edit_imageView);
        imageView.setAbsolutePath(imagePath);
        getContext().getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override
            public void run() {
                XRichText.getInstance().loadImage(imagePath, imageView, rtImageHeight);

                allLayout.addComponent(imageLayout, index);
            }
        });
    }

    public int getRtImageHeight() {
        return rtImageHeight;
    }

    public void setRtImageHeight(int rtImageHeight) {
        this.rtImageHeight = rtImageHeight;
    }

    public int getRtImageBottom() {
        return rtImageBottom;
    }

    public void setRtImageBottom(int rtImageBottom) {
        this.rtImageBottom = rtImageBottom;
    }

    public String getRtTextInitHint() {
        return rtTextInitHint;
    }

    public void setRtTextInitHint(String rtTextInitHint) {
        this.rtTextInitHint = rtTextInitHint;
    }

    public int getRtTextSize() {
        return rtTextSize;
    }

    public void setRtTextSize(int rtTextSize) {
        this.rtTextSize = rtTextSize;
    }

    public Color getRtTextColor() {
        return rtTextColor;
    }

    public void setRtTextColor(Color rtTextColor) {
        this.rtTextColor = rtTextColor;
    }

    public int getRtTextLineSpace() {
        return rtTextLineSpace;
    }

    public void setRtTextLineSpace(int rtTextLineSpace) {
        this.rtTextLineSpace = rtTextLineSpace;
    }
}
